package com.ak.game.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ak.game.entity.PnVipUser;
import com.ak.game.exception.ServiceException;
import com.ak.game.mapper.PnVipUserMapper;
import com.ak.game.service.PnVipUserService;
import com.ak.game.util.CommonUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.CompletableFuture;

/**
 * vip用户表(PnVipUser)表服务实现类
 *
 * @author makejava
 * @since 2024-05-17 19:45:51
 */
@Slf4j
@Service
public class PnVipUserServiceImpl extends ServiceImpl<PnVipUserMapper, PnVipUser> implements PnVipUserService {

    @Autowired
    private PnVipUserMapper vipUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 用户是否登录
     *
     * @param data
     * @return
     */
    @Override
    public boolean loginIn(Object data) {
        HashMap dataMap = (HashMap) data;
        if (ObjectUtil.isNull(dataMap)) throw new ServiceException("10005");
        // 异步编排根据userId查询用户信息
        CompletableFuture<PnVipUser> vipUserCompletableFuture = CommonUtil.fetchAndVerifyEntity(dataMap.get("user_id") + "", vipUserMapper::selectById, "10001");
        // 异步编排根据用户信息binding手机号从redis里查询登录的token信息
        CompletableFuture<String> redisTokenFuture = vipUserCompletableFuture.thenCompose(t -> {
            return CommonUtil.fetchAndVerifyEntity(t.getBinding(), (k) -> {
                return redisTemplate.opsForValue().get("pn_login_key:" + k);
            }, "10003");
        });
        String token = "";
        try {
            token = redisTokenFuture.get();
        } catch (Exception e) {
            log.error(String.format("验证用户登录状态失败：%s", e.getCause().getMessage()));
            throw new ServiceException(e.getCause().getMessage());
        }
        log.info("传递过来的token信息：{}", dataMap.get("token"));
        log.info("Redis中的登录token：{}", token);
        return token.equals("\"" + dataMap.get("token") + "\"");
    }
}
